<template>
	<div>
	  <el-row :gutter="20" class="search-row">
		<el-col :span="6">
		  <label style="font-weight: bold;">请输入司机用户名</label>
		</el-col>
		<el-col :span="10">
		  <el-input v-model="searchName" placeholder="输入司机用户名进行搜索" clearable @clear="handleClear"/>
		</el-col>
		<el-col :span="8">
		  <el-button type="danger" @click="loadDriverList()" round>搜索</el-button>
		  <el-button type="primary" @click="showAddDialog" round>添加司机</el-button>
		</el-col>
	  </el-row>

	  <!-- 添加司机对话框 -->
	  <el-dialog v-model="addDialogVisible" title="添加司机" label-width="auto">
		<el-form :model="addForm">
		  <el-form-item label="用户ID">
			<el-input v-model="addForm.userId"></el-input>
		  </el-form-item>
		  <el-form-item label="车牌号">
			<el-input v-model="addForm.vehiclePlate"></el-input>
		  </el-form-item>
		  <el-form-item label="车型">
			<el-input v-model="addForm.vehicleModel"></el-input>
		  </el-form-item>
		  <el-form-item label="车辆类型">
			<el-select v-model="addForm.vehicleType" placeholder="请选择车辆类型">
			  <el-option label="快车" value="快车" />
			  <el-option label="商务车" value="商务车" />
			  <el-option label="豪华车" value="豪华车" />
			</el-select>
		  </el-form-item>
		  <el-form-item label="车辆颜色">
			<el-input v-model="addForm.vehicleColor"></el-input>
		  </el-form-item>
		</el-form>
		<template #footer>
		  <el-button @click="addDialogVisible = false">取消</el-button>
		  <el-button type="primary" @click="addDriver">确定</el-button>
		</template>
	  </el-dialog>

	  <!-- 编辑司机对话框 -->
	  <el-dialog v-model="editDialogVisible" title="编辑司机" label-width="auto" style="max-width: 800px">
		<el-form :model="editForm">
		  <el-form-item label="司机编号">
			<el-input v-model="editForm.driverId" disabled></el-input>
		  </el-form-item>
		  <el-form-item label="用户ID">
			<el-input v-model="editForm.userId" disabled></el-input>
		  </el-form-item>
		  <el-form-item label="用户名 ">
			<el-input v-model="editForm.username" disabled></el-input>
		  </el-form-item>
		  <el-form-item label="车牌号">
			<el-input v-model="editForm.vehiclePlate"></el-input>
		  </el-form-item>
		  <el-form-item label="车型">
			<el-input v-model="editForm.vehicleModel"></el-input>
		  </el-form-item>
		  <el-form-item label="车辆类型">
			<el-select v-model="editForm.vehicleType" placeholder="请选择车辆类型">
			  <el-option label="快车" value="快车" />
			  <el-option label="商务车" value="商务车" />
			  <el-option label="豪华车" value="豪华车" />
			</el-select>
		  </el-form-item>
		  <el-form-item label="车辆颜色">
			<el-input v-model="editForm.vehicleColor"></el-input>
		  </el-form-item>
		  <el-form-item label="司机评分">
			<el-input v-model="editForm.rating"></el-input>
		  </el-form-item>
		  <el-form-item label="司机创建时间">
			<el-input v-model="editForm.driverCreateTime" disabled></el-input>
		  </el-form-item>
		  <el-form-item label="用户创建时间">
			<el-input v-model="editForm.userCreateTime" disabled></el-input>
		  </el-form-item>
		</el-form>

		<template #footer>
		  <el-button @click="editDialogVisible = false">取消</el-button>
		  <el-button type="primary" @click="updateDriver">确定</el-button>
		</template>
	  </el-dialog>

	  <el-table :data="driverList" stripe border show-overflow-tooltip table-layout="fixed">
		<el-table-column prop="driverId" label="司机编号" />
		<el-table-column prop="userId" label="用户ID" />
		<el-table-column prop="username" label="用户名" />
		<!-- 移除邮箱和头像表格列 -->
		<el-table-column prop="vehiclePlate" label="车牌号" />
		<el-table-column prop="vehicleModel" label="车型" />
		<el-table-column prop="vehicleType" label="车辆类型" />
		<el-table-column prop="vehicleColor" label="车辆颜色" />
		<el-table-column prop="rating" label="司机评分" />
		<el-table-column prop="driverCreateTime" label="司机创建时间">
		  <template #default="scope">
			{{ formatTimestamp(scope.row.driverCreateTime) }}
		  </template>
		</el-table-column>
		<el-table-column prop="userCreateTime" label="用户创建时间">
		  <template #default="scope">
			{{ formatTimestamp(scope.row.userCreateTime) }}
		  </template>
		</el-table-column>
		<el-table-column align="right" label="操作" width="150">
		  <template #default="scope">
			<el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
			<el-button size="small" type="danger" @click="deleteRow(scope.$index,scope.row)">删除</el-button>
		  </template>
		</el-table-column>
	  </el-table>

	  <el-pagination
		@size-change="handleSizeChange"
		@current-change="handleCurrentChange"
		:current-page="pagination.page"
		:page-sizes="[5, 10, 20]"
		:page-size="pagination.limit"
		layout="total, sizes, prev, pager, next, jumper"
		:total="pagination.total"
	  />
	</div>
  </template>

  <script>
  import { ElMessage } from "element-plus";
  import { DriverDetailControllerService } from "../../api/services/DriverDetailControllerService";
  import { formatTimestamp } from "../util/TimeUtil.js";
  import { UserControllerService } from '../../api/services/UserControllerService';

  export default {
	data() {
	  return {
		driverList: [],
		searchName: "",
		addDialogVisible: false,
		editDialogVisible: false,
		addForm: {
		  userId: "",
		  vehiclePlate: "",
		  vehicleModel: "",
		  vehicleType: "",
		  vehicleColor: "",
		},
		editForm: {
		  driverId: "",
		  userId: "",
		  username: "",
		  vehiclePlate: "",
		  vehicleModel: "",
		  vehicleType: "",
		  vehicleColor: "",
		  rating: "",
		  driverCreateTime: "",
		  userCreateTime: "",
		},
		pagination: {
		  page: 1, // 当前页码
		  limit: 10, // 每页行数
		  total: 0, // 总记录数
		},
	  };
	},
	created() {
	  this.loadDriverList();
	},
	methods: {
	  formatTimestamp,
	  async loadDriverList() {
		const res = await DriverDetailControllerService.selectByPage(
		  this.searchName,
		  this.pagination.page,
		  this.pagination.limit
		);
		if (res.code === 0) {
		  this.driverList = res.data;
		  this.pagination.total = res.count;
		} else {
		  ElMessage.error(res.msg);
		}
	  },
	  handleSizeChange(val) {
		this.pagination.limit = val;
		this.loadDriverList();
	  },
	  handleCurrentChange(val) {
		this.pagination.page = val;
		this.loadDriverList();
	  },
	  showAddDialog() {
		this.addDialogVisible = true;
		this.addForm = {
		  username: "",
		  userId: "",
		  vehiclePlate: "",
		  vehicleModel: "",
		  vehicleType: "",
		  vehicleColor: "",
		};
	  },
	  showEditDialog(row) {
		this.editDialogVisible = true;
		this.editForm = {
		  driverId: row.driverId,
		  userId: row.userId,
		  username: row.username,
		  vehiclePlate: row.vehiclePlate,
		  vehicleModel: row.vehicleModel,
		  vehicleType: row.vehicleType,
		  vehicleColor: row.vehicleColor,
		  rating: row.rating,
		  driverCreateTime: row.driverCreateTime,
		  userCreateTime: row.userCreateTime,
		};
	  },
	  async addDriver() {
		// 验证用户 ID 是否存在
		if (!this.addForm.userId) {
		  ElMessage.error('请输入用户 ID');
		  return;
		}
		try {
		  const userRes = await UserControllerService.getUserById(parseInt(this.addForm.userId));
		  if (userRes.code !== 0 || !userRes.data) {
		    ElMessage.error('无法找到该用户，无法添加司机');
		    return;
		  }

		  const res = await DriverDetailControllerService.insert(this.addForm);
		  if (res.code === 0) {
		    ElMessage.success('添加司机成功');
		    this.addDialogVisible = false;
		    this.loadDriverList();
		  } else {
		    ElMessage.error(res.msg);
		  }
		} catch (error) {
		  ElMessage.error('系统错误，请稍后重试');
		  console.error(error);
		}
	  },
	  async updateDriver() {
		try {
		  const requestBody = {
			driverId: this.editForm.driverId,
			userId: this.editForm.userId,
			username: this.editForm.username,
			// 移除 email 和 avatar 字段
			vehiclePlate: this.editForm.vehiclePlate,
			vehicleModel: this.editForm.vehicleModel,
			vehicleType: this.editForm.vehicleType,
			vehicleColor: this.editForm.vehicleColor,
			rating: this.editForm.rating,
		  };
		  const res = await DriverDetailControllerService.update(requestBody);
		  if (res.code === 0) {
			ElMessage.success("更新成功");
			this.editDialogVisible = false;
			this.loadDriverList();
		  } else {
			ElMessage.error(res.msg);
		  }
		} catch (error) {
		  ElMessage.error("网络错误");
		}
	  },
	  async deleteRow(index, row) {
		this.$confirm("确认删除该司机吗?", "提示", {
		  confirmButtonText: "确定",
		  cancelButtonText: "取消",
		  type: "warning",
		})
		  .then(async () => {
			try {
			  const res = await DriverDetailControllerService.deleteById(row.driverId);
			  if (res.code === 0) {
				ElMessage.success("删除成功");
				this.loadDriverList();
			  } else {
				ElMessage.error(res.msg);
			  }
			} catch (error) {
			  ElMessage.error("网络错误");
			}
		  })
		  .catch(() => {
			this.$message.info("已取消删除");
		  });
	  },
	  handleClear() {
		this.loadDriverList();
	  },
	},
  };
  </script>

  <style scoped>
  .search-row {
	margin-bottom: 20px;
  }

  .el-button {
	margin-left: 10px;
  }
  </style>
